const app = getApp();
// console.log(app.globalData.api);  
let api = app.globalData.api;// 访问全局变量
Page({
  data: {
    words: [],
    type: 3,//喜欢类型
    tempWords: [],//在页面呈现的样子
    showPopup: false,
    selectedWord: {},
    searchContent: '',
    isFocus: false,
    userInfo: {}
  },

  onShow: function () {
    let userInfo = wx.getStorageSync('loginUser');
    this.setData({
      'userInfo': userInfo,
    });
    setTimeout(()=>{
      this.getMyNewWordNote();//从数据库里获取生词
    }, 10);
    setTimeout(() => {
      this.wordsOperate();
    }, 500)
  },

  //数据处理，将过长的中文进行省略号处理
  wordsOperate(){
    //深拷贝（只适用于可以被序列化为 JSON 的数据）
    let tempArr = JSON.parse(JSON.stringify(this.data.tempWords));
    tempArr.forEach(element => {//对数据进行处理，过长的显示省略号
      if (element.translation.length >= 4) {
        element.translation = element.translation.slice(0, 4) + '...'
      }
    });
    this.setData({
      'tempWords': tempArr
    });
    console.log("tempWords==>", this.data.tempWords);
  },

  searchContent(e){
    console.log(e.detail.value);
    this.setData({
      'searchContent': e.detail.value
    });
  },
//搜索单词
  searchWords(){
    console.log("关键字==>", this.data.searchContent);
    if(this.data.searchContent == '' || this.data.searchContent == null){
      this.setData({
        'tempWords': this.data.words
      });
    }else{
      //深拷贝（只适用于可以被序列化为 JSON 的数据）
      let tempArr = JSON.parse(JSON.stringify(this.data.words));
      const reg = new RegExp(this.data.searchContent, 'i') // 不区分大小写
      tempArr = tempArr.filter(item=>(reg.test(item.word) || reg.test(item.translation)));
      console.log("tempArr==>", tempArr);
      this.setData({
        'tempWords': tempArr
      });
    }
    setTimeout(() => {
      this.wordsOperate();//数据处理
    }, 200)
  },

  //获取我的所有生词
  getMyNewWordNote() {
    let that = this;
    wx.request({
      url: api + '/user/searchMyWordsByType/' + this.data.userInfo.id + '/' + this.data.type,
      method: 'GET',
      success: (res) => {
        console.log('请求成功');
        console.log(res.data)
        if (res.data.code == 200) {
          that.setData({
            'words': res.data.data,
            'tempWords': res.data.data
          });
          console.log("生词本数据获取成功！", this.data.words);
        } else {
          wx.showToast({
            title: '数据获取异常',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '数据请求错误',
          icon: 'none'
        })
      }
    })
  },

  rememberWord: function (e) {
    // 获取当前单词信息
    let id = e.currentTarget.dataset.id;//需要删除的单词的id
    // let index = e.currentTarget.dataset.index;//需要删除的单词的索引
    let that = this;
    // 调用API传数据到后端
    wx.request({
      url: api+'/user/deleteWord/'+id,
      method: 'POST',
      success: (res)=>{
        console.log(res.data);
        if(res.data.code == 200){
          wx.showToast({
            title: '移出成功',
            icon: 'none'
          });
          let tempArr = that.data.tempWords;
          let tempWords = that.data.words;
          tempArr = tempArr.filter(item=> item.id !== id);//进行删除
          tempWords = tempWords.filter(item=> item.id !== id);
          that.setData({
            'words': tempWords,
            'tempWords': tempArr
          });
          that.wordsOperate();
        }
      },
      fail: (err)=>{
        console.log(err);
        wx.showToast({
          title: '删除数据出现异常',
          icon: 'none'
        });
      }
    })
  },


  navigateBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },

  showWordDetail: function (e) {
    // 获取点击的单词信息
    let index = e.currentTarget.dataset.index;
    let selected = this.data.words[index];
    console.log("select==>" + selected + "###  trans==>" + selected.translation);
    // 显示单词详情弹窗
    this.setData({
      'showPopup': true,
      'selectedWord': selected
    });
  },

  closePopup: function () {
    // 关闭弹窗
    this.setData({
      'showPopup': false,
      'selectedWord': {}
    });
  },

  onFocus: function (e) {
    this.setData({
      'isFocus': true
    });
  },
  onBlur: function (e) {
    this.setData({
      'isFocus': false
    });
  },
});
